const express = require('express');
const Router = express.Router(); // ==app
let query = require("../../db/mysql.js");

//加入订单
Router.post("/addorder", async (req, res) => {
    let { username } = req.body;
    let data = {};
    try {
        let sql = `select gid,gcount,size,color from shoppingcart where ischeck='1' and username='${username}'`;
        let p = await query(sql);
        let calcStr = '';
        let calcStr2 = '';
        let gcount = '';
        let gids = '';
        let sizes = '';
        let colors = '';
        let editCount = '';
        let aStr = '';
        let insertStr = '';
        let insertStr2 = '';
        let newStr = '';
        let a = '';
        let b = '';
        let c = '';
        if (p.length) {
            // console.log(p);
            p.forEach(item => {
                gids += `'${item.gid}',`;
                sizes += `'${item.size}',`;
                colors += `'${item.color}',`;
            })
            gids = gids.slice(0, -1);
            sizes = sizes.slice(0, -1);
            colors = colors.slice(0, -1);
            // console.log(gids);
            //判断订单表里面有没有相同数据，有就合并
            calcStr = `select gid,gcount from goodsorder where gid in(${gids}) and username='${username}' and color in(${colors}) and size in(${sizes})`;
            // console.log(calcStr);
            // console.log(calcStr);
            let count = await query(calcStr);
            // console.log(count);
            if (count.length) {
                calcStr2 = `select gid,gcount,size,color from shoppingcart where ischeck='1' and username='${username}' and (gid not in (select gid from goodsorder) or color not in (select color from goodsorder) or size not in (select size from goodsorder))`;
                let count2 = await query(calcStr2);
                // console.log(count2);
                if (count2.length) {//在有相同数据中 看看有没有不相同的 有就新增
                    // console.log(count2);
                    count2.forEach(item => {
                        insertStr2 += `('${username}','${item.gid}','${item.gcount}','${item.color}','${item.size}'),`
                    })
                    insertStr2 = insertStr2.slice(0, -1);
                    newStr = `insert into goodsorder(username,gid,gcount,color,size) values${insertStr2}`;
                    // console.log(newStr);
                }
                for (let i in p) {
                    for (let key in count) {
                        if (p[i].gid == count[key].gid) {
                            // console.log(p[key].gcount,count[key].gcount);
                            gcount = p[i].gcount + count[key].gcount;
                            // aStr += ' when ' + p[key].gid + ' then ' + gcount
                            aStr += ` when ${count[key].gid} then ${gcount}`;
                        }
                    }
                }
                // console.log(aStr);
                //多对多合并数据
                editCount = `update goodsOrder set gcount=(case gid ${aStr} end) where username='${username}'`;
                let istrue = false;
                b = await query(editCount);
                if (newStr != '') {
                    // console.log(newStr);
                    a = await query(newStr);
                    if (a.affectedRows && b.affectedRows) {
                        istrue = true;
                    }
                } else {
                    if (b.affectedRows) {
                        istrue = true;
                    }
                }
                if (istrue) {
                    data = {
                        code: 2000,
                        flag: true,
                        message: '增加成功'
                    }
                } else {
                    data = {
                        code: 3000,
                        flag: false,
                        message: '增加失败'
                    }
                }
            } else {
                //没有就新增
                p.forEach(item => {
                    insertStr += `('${username}','${item.gid}','${item.gcount}','${item.color}','${item.size}'),`
                })
                insertStr = insertStr.slice(0, -1);
                editCount = `insert into goodsorder(username,gid,gcount,color,size) values${insertStr}`;
                c = await query(editCount);
                if (c.affectedRows) {
                    data = {
                        code: 2000,
                        flag: true,
                        message: '增加成功'
                    }
                } else {
                    data = {
                        code: 3000,
                        flag: false,
                        message: '增加失败'
                    }
                }
            }
            // console.log(editCount);
        }
    } catch (err) {
        // console.log(err);
        data = {
            code: 5000,
            flag: false,
            message: '服务器出错'
        }
    }
    res.send(data);
});

//删除订单
Router.delete("/delorder", async (req, res) => {
    let { username, gid, color, size } = req.body;
    let data = {};
    try {
        let sql = `delete from goodsorder where username='${username}' and gid='${gid}' and color='${color}' and size='${size}'`;
        let p = await query(sql);
        if (p.affectedRows) {
            data = {
                code: 2000,
                flag: true,
                message: '删除成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '删除失败'
            }
        }
    } catch (err) {
        data = {
            code: 5000,
            flag: false,
            message: '服务器出错'
        }
    }
    res.send(data);
})

//获取订单列表
Router.get("/getorder", async (req, res) => {
    let { username } = req.query;
    let data = {};
    let goodinfo = '';
    let infoSql;
    try {
        let sql = `select gid,gcount,color,size from goodsorder where username='${username}'`;//获取订单gid
        let p = await query(sql);
        if (p.length) {
            p.forEach(item => {
                goodinfo += item.gid + ',';
            })
            // console.log(p);
            goodinfo = goodinfo.slice(0, -1);
            infoSql = `select * from goodsinfo where gid in(${goodinfo})`;//获取订单的商品信息
            let d = await query(infoSql);
            // console.log(d);
            if (d.length) {
                p.forEach(item => {
                    d.forEach(ps => {
                        if (item.gid == ps.gid) {
                            item.typeId = ps.typeId;
                            item.kid = ps.kid;
                            item.gname = ps.gname;
                            item.gimg = ps.gimg;
                            item.gprice = ps.gprice;
                            item.gstock = ps.gstock;
                        }
                    })
                })
                // console.log(arr);
                data = {
                    code: 2000,
                    flag: true,
                    totalcount: p.length,
                    message: '搜索成功',
                    data: p
                }
            } else {
                data = {
                    code: 3000,
                    flag: false,
                    message: '搜索失败'
                }
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '搜索失败'
            }
        }
    } catch (err) {
        data = {
            code: 5000,
            flag: false,
            message: '服务器出错'
        }
    }
    res.send(data);
})
//分页获取订单列表
Router.get("/searchorder", async (req, res) => {
    let { page, pagesize } = req.query;
    let data = {};
    let goodinfo = '';
    let infoSql;
    page = page || 1;
    pagesize = pagesize || 5;
    let index = (page - 1) * pagesize;
    try {
        let sql = `select * from goodsorder where gid limit ${index},${pagesize}`;//获取订单gid,gcount,color,size
        let p = await query(sql);
        if (p.length) {
            p.forEach(item => {
                goodinfo += `'${item.username}',`;
            })
            // console.log(p);
            goodinfo = goodinfo.slice(0, -1);
            infoSql = `select * from user where username in(${goodinfo})`;//获取订单的商品信息
            let d = await query(infoSql);
            // console.log(d);
            if (d.length) {
                p.forEach(item => {
                    d.forEach(ps => {
                        if (item.username == ps.username) {
                            item.phonenum = ps.phonenum;
                            item.address = ps.address;
                        }
                    })
                })
                // console.log(arr);
                data = {
                    code: 2000,
                    flag: true,
                    totalcount: p.length,
                    message: '搜索成功',
                    data: p
                }
            } else {
                data = {
                    code: 3000,
                    flag: false,
                    message: '搜索失败'
                }
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '搜索失败'
            }
        }
    } catch (err) {
        data = {
            code: 5000,
            flag: false,
            message: '服务器出错'
        }
    }
    res.send(data);
})

//订单查询
Router.get("/searchorders", async (req, res) => {
    let { username } = req.query;
    let data = {};
    let goodinfo = '';
    let infoSql;
    try {
        let sql = `select * from goodsorder where username like '%${username}%'`;
        let p = await query(sql);
        if (p.length) {
            p.forEach(item => {
                goodinfo += `'${item.username}',`;
            })
            // console.log(p);
            goodinfo = goodinfo.slice(0, -1);
            // console.log(goodinfo);
            infoSql = `select * from user where username in(${goodinfo})`;//获取订单的商品信息
            let d = await query(infoSql);
            // console.log(d);
            if (d.length) {
                p.forEach(item => {
                    d.forEach(ps => {
                        if (item.username == ps.username) {
                            item.phonenum = ps.phonenum;
                            item.address = ps.address;
                        }
                    })
                })
                // console.log(arr);
                data = {
                    code: 2000,
                    flag: true,
                    totalcount: p.length,
                    message: '搜索成功',
                    data: p
                }
            } else {
                data = {
                    code: 3000,
                    flag: false,
                    message: '搜索失败'
                }
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '搜索失败'
            }
        }
    } catch (err) {
        data = {
            code: 5000,
            flag: false,
            message: '服务器出错'
        }
    }
    res.send(data);
})

Router.put('/editorder/:id', async (req, res) => {
    let { id } = req.params;
    let str = ``;
    for (let key in req.body) {
        str += `${key}='${req.body[key]}',`
    }
    str = str.slice(0, -1);
    let data = {};
    try {
        let sql = `update goodsorder set ${str} where id='${id}'`;
        let p = await query(sql);
        if (p.affectedRows) {
            data = {
                code: 2000,
                flag: true,
                message: '修改成功'
            }
        } else {
            data = {
                code: 3000,
                flag: false,
                message: '修改失败',
            }
        }
    } catch (err) {
        data = {
            code: 5000,
            flag: false,
            message: '服务器出错',
        }
    }
    res.send(data);
})

module.exports = Router;